<!--
 * @Author: Bennty
 * @Date: 2024-07-30 13:37:23
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-11-06 16:42:22
 * @Description: 请填写简介
-->
<template>
    <div class="p-2">
        <transition 
        :enter-active-class="proxy?.animate.searchAnimate.enter"
        :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search">
                <el-form :model="queryParams" :inline="true" ref="queryFormRef">
                    <el-form-item label="产品大类" prop="productCategoriesType">
                        <el-select v-model="queryParams.productCategoriesType" placeholder="请选择">
                            <el-option v-for="item in total_catagory" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="产品小类" prop="productSubcategoryType">
                        <el-select v-model="queryParams.productSubcategoryType" placeholder="请选择">
                            <el-option v-for="item in single_catagory" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="工费录入状态" prop="laborCostsStatus">
                        <el-select v-model="queryParams.laborCostsStatus">
                            <el-option label="已录入" :value="1"></el-option>
                            <el-option label="未录入" :value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="模糊搜索" prop="productName">
                        <el-input v-model="queryParams.bomName" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="8" class="mb8">
                    <el-col class="header-button-container" :span="1.5">
                        <el-button type="success" plain icon="Plus" @click="handleClickAdd">新增</el-button>
                    </el-col>
                </el-row>
            </template>
            <el-table :data="productList" class="product-table">
                <el-table-column label="产品大类" prop="productCategoriesName" align="center"></el-table-column>
                <el-table-column label="产品小类" prop="productSubcategoryName" align="center"></el-table-column>
                <el-table-column label="产品名称" prop="bomName" align="center"></el-table-column>
                <el-table-column label="效果图录入状态" align="center">
                    <template #default="scope">
                        <span class="done" v-if="scope.row.renderingsUrl">已录入</span>
                        <el-button link class="undone" v-else @click="handleClickRecordImage">未录入</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="文档录入状态" align="center">
                    <template #default="scope">
                        <span class="done" v-if="scope.row.sourceFile">已录入</span>
                        <el-button link @click="handleClickFileRecord" class="undone" v-else>未录入</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="工费录入状态" align="center">
                    <template #default="scope">
                        <span class="done" v-if="scope.row.laborCostsStatus == 1">已录入</span>
                        <span class="undone" v-else="scope.row.laborCostsStatus == 1">未录入</span>
                        <!-- <el-button link class="undone" v-else @click="handleClickRecordCost(scope.row)">未录入</el-button> -->
                    </template>
                </el-table-column>
                <el-table-column label="最低库存" prop="highInventory" align="center"></el-table-column>
                <el-table-column label="最高库存" prop="lowInventory" align="center"></el-table-column>
                <el-table-column label="产品激活状态" align="center">
                    <template #default="scope">
                        <el-button link class="inactive" v-if="scope.row.salesActiveStatus == '0'" @click="handleClickSalerActive(scope.row)">未激活</el-button>
                        <el-button link class="saler-active" v-else-if="scope.row.salesActiveStatus == '1' && scope.row.financeActiveStatus == '0'" @click="handleClickFiancerActive(scope.row)">销售已激活</el-button>
                        <span class="actived" v-else-if="scope.row.financeActiveStatus == '1' && scope.row.financeActiveStatus == '1'">已激活</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-tooltip content="编辑" placement="top">
                            <el-button link :style="{fontSize:'15px'}" type="primary" icon="Edit" @click="handleClickEdit(scope.row)" ></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button link :style="{fontSize:'15px',color:'#F75C4E'}" icon="Delete" @click="handleClickDelete(scope.row)"></el-button>
                        </el-tooltip>
                        <!-- <el-tooltip content="快速下单" placement="top">
                            <el-button link :style="{fontSize:'15px'}" type="warning" icon="DocumentAdd" @click="handleClickFastOrder(scope.row)"></el-button>
                        </el-tooltip> -->
                        <el-tooltip content="查看下单记录" placement="top">
                            <el-button link :style="{fontSize:'15px',color:'#B886F8'}"  icon="View" @click="handleClickOrderRecord(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="totalData > 0" :total="totalData" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getBomList" />
        </el-card>
        <salerActive :visible="salerActiveVisible" :data="productDetail" @close="handleCloseSalerActive" @submit="handleSubmitSalerActive" />
        <financerActive :visible="financerActiveVisible" :data="productDetail" @close="handleCloseFiancerActive" @submit="handleSubmitFiancerActive" />
        <el-dialog v-model="recordCostVisible" title="工费录入">
            <el-form :model="costData" label-width="auto">
                <el-form-item label="产品名称" label-position="right">
                    <span>{{ recordCostProduct.productName }}</span>
                </el-form-item>
                <el-form-item label="热收缩包装" label-position="right">
                    <el-row :gutter="30">
                        <el-col :span="12">
                            <el-input placeholder="工费" v-model="costData.packageCost"></el-input>
                        </el-col>
                        <el-col :span="12">
                            <el-input placeholder="积分" v-model="costData.packagePoint"></el-input>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="组装" label-position="right">
                    <el-row :gutter="30">
                        <el-col :span="12">
                            <el-input placeholder="工费" v-model="costData.assembleCost"></el-input>
                        </el-col>
                        <el-col :span="12">
                            <el-input placeholder="积分" v-model="costData.assembleCost"></el-input>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button  type="primary" @click="handleSubmitRecordCost" >确 定</el-button>
                    <el-button @click="handleCloseRecordCost">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="recordImageVisible" title="效果图录入" @close="handleCloseRecordImage">
            <el-form>
                <el-form-item label="选择图片">
                    <el-upload ref="ImageUpload" 
                        :action="uploadImgUrl" 
                        :headers="headers"
                        :limit="1"
                        :before-upload="beforeImageUpload"
                        :on-success="handleImageSuccess"
                        style="width: 30%"
                    >
                        <template #trigger>
                            <el-button type="primary">选择文件</el-button>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button  type="primary" @click="handleSbumitRecordImage" >确 定</el-button>
                    <el-button @click="handleCloseRecordImage">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="recordFileVisible" title="文档录入">
            <el-form>
                <el-form-item label="选择文件">
                    <el-upload ref="fileUpload" 
                        :action="uploadImgUrl" 
                        :headers="headers"
                        :limit="1"
                        :before-upload="beforeFileUpload"
                        :on-success="handleFileSuccess"
                        style="width: 30%"
                    >
                        <template #trigger>
                            <el-button type="primary">选择文件</el-button>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button  type="primary"  >确 定</el-button>
                    <el-button @click="handleCloseFileRecord">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <el-drawer v-model="fastOrderVisible" title="快速下单" size="45%" @close="handleClockFastOrder">
            <el-form :inline="true">
                <el-form-item label="产品名称">
                    <span>{{ productDetail.bomName }}</span>
                </el-form-item>
                <el-form-item label="当前可用成品库存">
                    <span>{{ productDetail.lowInventory }}</span>
                </el-form-item>
            </el-form>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-input type="number" v-model.number="fastOrderNumber" placeholder="一键下单数量"></el-input>
                </el-col>
                <el-col :span="12">
                    <el-button type="success" plain :disabled="shouldClickFastOrder" @click="handleClickOrder">一键下单</el-button>
                </el-col>
            </el-row>
            <div class="product-info" >
                <h4>产品配置信息</h4>
                <el-card shadow="never">
                    <template #header>
                        <span class="card-title">半成品</span>
                    </template>
                    <el-form :model="fastOrderFormData.preparedProductsForm" ref="preparedFormRef" :rules="preparedFormRules">
                        <el-table :data="fastOrderFormData.preparedProductsForm">
                            <el-table-column label="半成品小类" prop="productSubcategoryName"></el-table-column>
                            <el-table-column label="具体名称及规格" prop="specsDetail"></el-table-column>
                            <el-table-column label="库存" prop="inventory"></el-table-column>
                            <el-table-column label="下单" >
                                <template #default="scope">
                                    <el-form-item :prop="`${scope.$index}.number`">
                                        <el-input type="number" v-model.number="fastOrderFormData.preparedProductsForm[scope.$index].number" />
                                    </el-form-item>
                                    
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form>
                </el-card>
                <el-card shadow="never" style="margin-top:15px">
                    <template #header>
                        <span class="card-title">辅材</span>
                    </template>
                    <el-table :data="fastOrderFormData.auxiliariesForm">
                        <el-table-column label="材料小类" prop="productSubcategoryName"></el-table-column>
                        <el-table-column label="具体名称及规格" prop="specsDetail"></el-table-column>
                        <el-table-column label="库存" prop="inventory"></el-table-column>
                        <el-table-column label="下单" >
                            <template #default="scope">
                                <el-input type="number" v-model.number="scope.row.number" :disabled="!scope.row.inventory" />
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
                <span class="tips">
                    *注:专版湿巾3万套起订，火柴最低起订量2500盒，并且只能按照2500的倍数追定，如果不满足条件无法保存
                </span>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button  type="primary" @click="handleSubmitFastOrder" >确 定</el-button>
                    <el-button @click="handleClockFastOrder">取 消</el-button>
                </div>
            </template>
        </el-drawer>
        <el-dialog v-model="orderRecordVisible" title="查询下单记录" @close="handleCloseOrderRecord">
            <el-form :inline="true" :model="recordQuery">
                <el-form-item label="产品名称">
                    <span>{{ checkedProduct.productName }}</span>
                </el-form-item>
                <el-form-item label="产品名称" prop="operator">
                    <el-select v-model="recordQuery.operator">
                        <el-option v-for="item in userList"
                        :key="item.userId" :label="item.nickName" :value="item.userId"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <el-timeline>
                <el-timeline-item v-for="(activity,index) in activities" :key="index" :timestamp="activity.timestamp">
                    {{ activity.content }}
                </el-timeline-item>
            </el-timeline>
            <template #footer>
                <div class="dialog-footer">
                    <el-button  type="primary" @click="handleCloseOrderRecord" >确 定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { type FormInstance,type UploadInstance, type UploadProps,type ElForm } from 'element-plus';
import { useRouter } from 'vue-router';
import { BOMVO } from '@/api/sj/warehouse/BOM/types';
import { globalHeaders } from "@/utils/request";
import { getBOMListApi, getBOMDetailApi, deleteBomApi,fastOrderBomApi } from '@/api/sj/warehouse/BOM';
import salerActive from './components/salerActive.vue';
import financerActive from './components/financerActive.vue';
import useCRMStore from '@/store/modules/crm';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const queryFormRef = ref<FormInstance>();
const productList = ref<BOMVO[]>([]);
const totalData = ref(0);
const salerActiveVisible = ref(false);
const financerActiveVisible = ref(false);
const recordCostVisible = ref(false);
const recordCostProduct = ref<any>();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const recordImageVisible = ref(false);
const ImageUpload = ref<UploadInstance>();
const recordFileVisible = ref(false);
const fileUpload = ref<UploadInstance>();
const fastOrderVisible = ref(false);
const fastOrderProduct = ref<any>();
const fastOrderNumber = ref<number | undefined>();
const shouldClickFastOrder = ref(true);
const preparedProducts = reactive<any[]>([]);
const auxiliaries = reactive<any[]>([]);
const orderRecordVisible = ref(false);
const checkedProduct = ref<any>();
const { userList,getUsers } = useCRMStore();
const productDetail = ref<any>();

const activities = ref<any[]>([
    {
        content: '半成品 小韩CAKE A款不锈钢外盒  下单100000',
        timestamp: '2024-07-27'
    },
    {
        content: '辅材 小韩CAKE 不锈钢专版二齿叉  下单100000',
        timestamp: '2024-07-26'
    },
    {
        content: '半成品 小韩CAKE A款不锈钢外盒  下单100000',
        timestamp: '2024-07-26'
    }
]);


const data = reactive({
    queryParams:{
        productCategoriesType: undefined,
        productSubcategoryType: undefined,
        laborCostsStatus: undefined,
        bomName: undefined,
        pageNum: 1,
        pageSize: 30
    },
    costData:{
        id: undefined,
        packageCost: undefined,
        assembleCost: undefined,
        packagePoint:  undefined,
        assemblePoint: undefined
    },
    imageData:{
        id: undefined,
        imageUrl: undefined
    },
    fileData:{
        id: undefined,
        fileUrl: undefined
    },
    fastOrderFormData:{preparedProductsForm:[...preparedProducts],auxiliariesForm:[...auxiliaries]},
    recordQuery:{
        operator: undefined
    }
});

const { total_catagory,single_catagory } = toRefs<any>(proxy?.useDict('total_catagory','single_catagory'));

const { queryParams, costData, imageData, fileData, fastOrderFormData, recordQuery } = toRefs(data);

const getBomList = async () => {
    const { rows, total } = await getBOMListApi(queryParams.value);
    productList.value = rows;
    totalData.value = total;
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getBomList();
};

const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

/** 新增BOM */
const handleClickAdd = ()=>{
    router.push('/warehouse/addBom');
};

/** 编辑BOM */
const handleClickEdit = (row: any) => {
    router.push(`/warehouse/editBom/${row.id}`);
};

/** 销售激活 */
const handleClickSalerActive = async (row:any)=>{
    const result = await getBOMDetailApi(row.id);
    if(result.code == 200){
        salerActiveVisible.value = true;
        productDetail.value = result.data;
    };
};

const handleSubmitSalerActive = (result: boolean) => {
    if(result){
        getBomList();
    };
};

const handleCloseSalerActive = ()=>{
    salerActiveVisible.value = false;
};

/** 财务激活 */
const handleClickFiancerActive = async (row:any)=>{
    const result = await getBOMDetailApi(row.id);
    if(result.code == 200){
        financerActiveVisible.value = true;
        productDetail.value = result.data;
    };
};

const handleSubmitFiancerActive = (result: boolean) => {
    if(result){
        getBomList();
    };
};

const handleCloseFiancerActive = ()=>{
    financerActiveVisible.value = false;
};

/** 删除 */
const handleClickDelete = async (row:any)=>{
    await proxy?.$modal.confirm("确认要把此条信息放入回收站？");
    const { code } = await deleteBomApi(row.id);
    if(code == 200){
        proxy?.$modal.msgSuccess("放入回收站成功");
        getBomList();
    };
    
};

/** 工费录入 */
const handleClickRecordCost = (row:any)=>{
    recordCostVisible.value = true;
    recordCostProduct.value = row;
    costData.value.id = row.id;
};

const handleCloseRecordCost = ()=>{
    recordCostVisible.value = false;
    costData.value.id = undefined;
    costData.value.packageCost = undefined;
    costData.value.packagePoint = undefined;
    costData.value.assembleCost = undefined;
    costData.value.assemblePoint = undefined;
};

const handleSubmitRecordCost = ()=>{
    handleCloseRecordCost();
};

/** 效果图录入 */
const handleClickRecordImage = (row:any)=>{
    recordImageVisible.value = true;
    imageData.value.id = row.id;
};

const beforeImageUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片大小不可超过 5MB!')
        return false;
    }
    return true;
};

const handleImageSuccess: UploadProps['onSuccess'] = (
    response
    ) => {
        imageData.value.imageUrl = response.data.url;
};

/** 关闭效果图录入 */
const handleCloseRecordImage = ()=>{
    recordImageVisible.value = false;
    imageData.value.id = undefined;
    ImageUpload.value?.clearFiles();
    imageData.value.imageUrl = undefined;
};

/** 提交效果图录入 */
const handleSbumitRecordImage = ()=>{
    handleCloseRecordImage();
};


/** 点击开始文件录入 */
const handleClickFileRecord = (row:any)=>{
    recordFileVisible.value = true;
    fileData.value.id = row.id;
};

const beforeFileUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('文件大小不可超过 5MB!')
        return false;
    }
    return true;
};

const handleFileSuccess: UploadProps['onSuccess'] = (
    response
    ) => {
        fileData.value.fileUrl = response.data.url;
};

/** 关闭文档录入 */
const handleCloseFileRecord = ()=>{
    recordFileVisible.value = false;
    fileData.value.id = undefined;
    fileUpload.value?.clearFiles();
    fileData.value.fileUrl = undefined;
};

/** 打开快速下单 */
const handleClickFastOrder = async (row:any)=>{
    
    fastOrderProduct.value = row;
    const {code, data} = await getBOMDetailApi(row.id);
    if(code == 200){
        productDetail.value = data;
        fastOrderVisible.value = true;
        if(data.auxiliaryMaterialsVos.length !==0){
            const auxiliaries = data.auxiliaryMaterialsVos.map((item: any)=>{
                return {
                    ...item,
                    number: undefined,
                    type: 2
                };
            });
            fastOrderFormData.value.auxiliariesForm = auxiliaries;
        };
        if(data.bomRelatSemiVos.length !== 0){
            const preparedProducts = data.bomRelatSemiVos.map((item: any)=>{
                return {
                    ...item,
                    number: undefined,
                    type: 1
                };
            });
            fastOrderFormData.value.preparedProductsForm = preparedProducts;
        };
    };
};

watch(()=>fastOrderNumber.value, ()=>{
    if(fastOrderNumber.value){
        shouldClickFastOrder.value = false;
    }else{
        shouldClickFastOrder.value = true;
    };
},{deep: true});

/** 点击一键下单按钮 */
const handleClickOrder = async ()=>{
    fastOrderNumber
    const preparedProductsData = fastOrderFormData.value.preparedProductsForm.map((item: any)=>{
        return {
            materialName: item.specsDetail,
            number: fastOrderNumber.value,
            type: item.type,
            productId: item.semiProductId,
            bomId: productDetail.value.id,
            bomName: productDetail.value.bomName
        };
    });
    const auxilariesData = fastOrderFormData.value.auxiliariesForm.map((item: any)=>{
        return {
            materialName: item.specsDetail,
            number: fastOrderNumber.value,
            type: item.type,
            productId: item.auxiliaryMaterialId,
            bomId: productDetail.value.id,
            bomName: productDetail.value.bomName
        }
    });
    const submitData = [...preparedProductsData, ...auxilariesData];
    const { code } = await fastOrderBomApi(submitData);
    if(code == 200){
        handleClockFastOrder();
        getBomList();
    };
};

const preparedFormRef = ref<InstanceType<typeof ElForm>>();
const checkInventory = (rule: any, value: number, callback: Function, row: any) => {
    if(value > row.inventory){
        callback(new Error('数量不可大于库存'));
    }else{
        callback();
    }
};
const preparedFormRules = ref(
    fastOrderFormData.value.preparedProductsForm.map((item: any,index: number)=>{
        number: [
            { required: true, message: '请输入数量', trigger: 'blur' },
            { validator: (rule: any, value: number, callback: Function) => checkInventory(rule, value, callback, item), trigger: 'blur' },
        ]
    })
);
    
const handleSubmitFastOrder = async () => {
    const preparedProductsData = fastOrderFormData.value.preparedProductsForm.map((item: any)=>{
        if(item.number){
            return {
                materialName: item.specsDetail,
                number: item.number,
                type: item.type,
                productId: item.semiProductId,
                bomId: productDetail.value.id,
                bomName: productDetail.value.bomName
            };
        };
    });

    const auxilariesData = fastOrderFormData.value.auxiliariesForm.map((item: any)=>{
        if(item.number){
            return {
                materialName: item.specsDetail,
                number: item.number,
                type: item.type,
                productId: item.auxiliaryMaterialId,
                bomId: productDetail.value.id,
                bomName: productDetail.value.bomName
            }
        };
    });
    const submitData = [...preparedProductsData, ...auxilariesData];
    const { code } = await fastOrderBomApi(submitData);
    if(code == 200){
        handleClockFastOrder();
        getBomList();
    };
};

const handleClockFastOrder = ()=>{
    fastOrderVisible.value = false;
    fastOrderProduct.value = {};
    fastOrderNumber.value = undefined;
};

const handleClickOrderRecord = (row:any)=>{
    orderRecordVisible.value = true;
    checkedProduct.value = row;
};

const handleCloseOrderRecord = ()=>{
    orderRecordVisible.value = false;
    recordQuery.value.operator = undefined;
};

onMounted(()=>{
    getBomList();
    getUsers();
});
</script>

<style lang="scss" scoped>
.product-table{
    .done{
        color: #68C23D;
        line-height: 10;
    }
    .undone{
        color: #F75C4E;
        line-height: 10;
    }
    .inactive{
        color: #F75C4E;
    }
    .saler-active{
        color: #69AFF0;
    }
    .actived{
        color: #68C23D;
    }
}
.dialog-footer{
    display: flex;
    justify-content: center;
}
.product-info{
    margin-top: 20px;
    .card-title{
        font-size:20px;
        font-weight: bloder;
    }
    .tips{
        display: block;
        color: red;
        margin-top: 15px;
    }
}
</style>